package com.woniu.demo.annotation;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by CHESHUAI on 2024/4/23 10:41
 */
public class MarkTest {

    public static List<String> filePathList = new ArrayList<>();

    public static void main(String[] args) {
        List<String> resultList = new ArrayList<>();
        String fileRootPath = "E:\\markTest\\";

        //检出的原图   分辨率x分辨率-水印值 & 被攻击图片文件夹名称
        String folderName = "960x540-06d6";
        String markStr = folderName.substring(folderName.indexOf('-')+1, folderName.length());


        File root = new File(fileRootPath + folderName); // 替换为你的文件夹路径
        walk(root);


        for (String filePath : filePathList) {

            String isSuccess = "失败";
            long time = 0;
            try {
                long beginTime = System.currentTimeMillis();
                //调用图片上传函数，并获取响应
                String respStr = httpUploadImg_J(filePath);

                long endTime = System.currentTimeMillis();
                time = endTime - beginTime;//毫秒数


                JSONObject obj = JSONObject.parseObject(respStr);

                String mark_id = String.valueOf(obj.get("mark_id"));
                if (!"null".equals(mark_id) && StringUtils.isNotBlank(mark_id)) {
                    if (mark_id.equals(markStr)) {
                        isSuccess = "成功";
                    } else {
                        isSuccess = "严重失败";
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            String result = "图片路径：" + filePath + "     " + isSuccess + "     用时：" + time;

            method1(fileRootPath + "\\"+folderName+"\\" + folderName + ".txt", result);

            resultList.add(result);
        }


        for (String result : resultList) {
            System.out.println(result);
        }

    }


    public static void walk(File dir) {

        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                //如果是子目录，则递归遍历该子目录
                walk(file);
            } else {
                //存文件路径
                filePathList.add(file.getAbsolutePath());
                System.out.println(file.getAbsolutePath());
            }
        }
    }


    /**
     * 使用HTTP上传图片
     * @param imgPath
     * @return
     */
    public static String httpUploadImg_J(String imgPath) {
        //设置超时时间
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 设置连接超时时间（单位为毫秒）
        factory.setConnectTimeout(3000);
        // 设置读取超时时间（单位为毫秒）
//        factory.setReadTimeout(60 * 1000);
        //发请求的
        RestTemplate restTemplate = new RestTemplate(factory);
        // 创建RestTemplate实例
        //RestTemplate restTemplate = new RestTemplate();


        // 准备文件
        File file = new File(imgPath);

        // 准备请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 创建请求实体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new FileSystemResource(file));
        body.add("api_key", "N3fMxS4faQRXz62ShnXRA7DkFPjGbf");
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 设置上传图片的URL
        String url = "http://60.204.223.104:8081/up_check";

        // 执行上传
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);

        // 输出结果
        System.out.println(response.getBody());

        return response.getBody();
    }


    public static void method1(String filePath, String appendStr) {
        FileWriter fw = null;
        try {
            //如果文件存在，则追加内容；如果文件不存在，则创建文件
            File f = new File(filePath);
            fw = new FileWriter(f, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.println(appendStr);
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
